﻿namespace EFS.RC.CC.Applications.Remote
{
	/// <summary>
	/// Remote application
	/// </summary>
	internal abstract class Application : EFS.RC.CC.Applications.Remote.Messaging
	{
		#region Constructor

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="applicationPresence"></param>
		public Application(Microsoft.Rtc.Collaboration.InstantMessagingCall applicationInstantMessagingCall) : base(applicationInstantMessagingCall)
		{
			// log
			EFS.EventLog.Log.LogInfo("Application", this);
		}

		#endregion

		#region Usage

		/// <summary>
		/// Send data message into the channel
		/// </summary>
		/// <param name="message"></param>
		/// <returns></returns>
		public System.IAsyncResult BeginDataSend(EFS.RC.CC.Messages.Message message)
		{
			// check
			EFS.Common.Verify.Reference(message, "message");

			// begin send context data
			return BeginDataSend(
				new System.Net.Mime.ContentType(EFS.RC.CC.Messages.Message.ContentType),
				EFS.RC.CC.Messages.Message.SerializeToByteArray(message));
		}

		#endregion

		#region Runtime

		/// <summary>
		/// Message received
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected abstract void OnMessageReceived(EFS.RC.CC.Messages.Message message);

		/// <summary>
		/// Message received
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected override void OnMessageReceived(System.Object sender, Microsoft.Rtc.Collaboration.InstantMessageReceivedEventArgs e)
		{
			try
			{
				// parse message
				OnMessageReceived(EFS.RC.CC.Messages.Message.Deserialize(e.MessageData.GetMessageBodyString()));
			}
			catch (System.Exception ex)
			{
				// just log
				EFS.EventLog.Log.LogException(ex, this);
			}
		}

		#endregion // Runtime
	}
}

